<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:deviceData:manager']"
        >{{$t('common.add')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="seriesIoEventList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('deviceData.popup.name')" align="center" prop="name" />
      <el-table-column :label="$t('deviceData.popup.associatedData')" align="center" prop="associatedData" >
        <template slot-scope="scope">
          {{seriesList.filter(o=> o.flag == scope.row.associatedData).map( o => o.name).join()}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('deviceData.popup.alarmLevel')" align="center" prop="alarmLevel" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.alarm_level" :value="scope.row.alarmLevel"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('deviceData.popup.expression')" align="center" prop="expression" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.display_expression" :value="scope.row.expression"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('deviceData.popup.threshold')" align="center" prop="threshold" />
      <el-table-column :label="$t('deviceData.popup.formula')" align="center" prop="formula" />
      <el-table-column :label="$t('deviceData.popup.alarmModel')" align="center" prop="alarmModel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.notify_model" :value="scope.row.alarmModel"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('deviceData.popup.alarmContent')" align="center" prop="alarmContent" />
      <el-table-column :label="$t('deviceData.popup.operation')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:deviceData:manager']"
          >{{$t('common.modify')}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:deviceData:manager']"
          >{{$t('common.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改事件定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="980px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item :label="$t('deviceData.popup.name')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('deviceData.popup.name')" />
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.associatedData')" prop="associatedData">
          <el-select v-model="form.associatedData" :disabled="!form.id" filterable :placeholder="$t('deviceData.popup.associatedData')" value-key="id">
            <el-option v-for="item in seriesList" :key="item.flag"  :label="item.name" :value="item.flag"  />  
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.alarmLevel')" prop="alarmLevel">
          <el-select v-model="form.alarmLevel" :placeholder="$t('deviceData.popup.alarmLevel')">
            <el-option
              v-for="dict in dict.type.alarm_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.expression')" prop="expression">
          <el-radio-group v-model="form.expression">
            <el-radio
              v-for="dict in dict.type.display_expression"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.threshold')" prop="threshold" v-if="form.expression!='NOT'">
          <el-input v-model="thresholds.start" :placeholder="$t('deviceData.popup.threshold')" v-if="form.expression!='BETWEEN'" />
          <el-col :span="11" v-if="form.expression=='BETWEEN'">
            <el-input v-model="thresholds.start" :placeholder="$t('deviceData.popup.startingValue')" style="width: 100%;"/>
          </el-col>
          <el-col class="line" :span="2" v-if="form.expression=='BETWEEN'"> - </el-col>
          <el-col :span="11" v-if="form.expression=='BETWEEN'">
            <el-input v-model="thresholds.end" :placeholder="$t('deviceData.popup.endingValue')" style="width: 100%;"/>
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.formula')" prop="formula" v-if="form.expression ==='NOT'">
          <el-input v-model="form.formula" :placeholder="$t('deviceData.popup.formula')" />
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.alarmModel')" prop="alarmModel">
          <el-select v-model="form.alarmModel" :placeholder="$t('deviceData.popup.alarmModel')">
            <el-option
              v-for="dict in dict.type.notify_model"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('deviceData.popup.alarmContent')">
          <el-input type="textarea" v-model="form.alarmContent" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('common.confirm')}}</el-button>
        <el-button @click="cancel">{{$t('common.cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSonsorEvent, getSonsorEvent, delSonsorEvent, addSonsorEvent, updateSonsorEvent } from "@/api/device/sonsorEvent";
import { seriesIoOptions} from "@/api/device/seriesIo";
export default {
  props:{
    deviceId:null,
    sensorId:null,
    sensorName:null,
    deviceTypeId:null
  },
  name: "SeriesIoEvent",
  dicts: ['notify_model','display_expression','alarm_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 事件定义表格数据
      seriesIoEventList: [],
      seriesList:[],
      thresholds:{ start:null,  end:null },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        seriesIoId: null,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: this.$t('common.cannotbeempty',{'name':this.$t('deviceData.popup.name')}), trigger: "blur" }
        ],
        expression: [
          { required: true, message: this.$t('common.cannotbeempty',{'name':this.$t('deviceData.popup.expression')}), trigger: "blur" }
        ],
        alarmModel: [
          { required: true, message: this.$t('common.cannotbeempty',{'name':this.$t('deviceData.popup.alarmModel')}), trigger: "change" }
        ],
        formula: [
          { required: true, message: this.$t('common.cannotbeempty',{'name':this.$t('deviceData.popup.formula')}), trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.queryParams.sensorId = this.sensorId
    this.queryParams.deviceId = this.deviceId
    this.getList();
    this.getSeriesIoOptions()
  },
  methods: {
    /** 查询事件定义列表 */
    getList() {
      this.loading = true;
      listSonsorEvent(this.queryParams).then(response => {
        this.seriesIoEventList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**获取控制按钮**/
    getSeriesIoOptions(){
        let params = {
          sensorId:this.sensorId,
          deviceTypeId:this.deviceTypeId,
          control:0
        }
        seriesIoOptions(params).then(res=>{
          this.seriesList = res.data;
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.thresholds = {start:null , end:null}
      this.form = {
        id: null,
        sensorId: this.sensorId,
        deviceId:this.deviceId,
        expression: 'NOT',
        alarmLevel:'ONE',
        formula:null ,
        name: this.sensorName,
        threshold: null,
        alarmModel: null,
        alarmContent: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title =  this.$t('deviceData.addAlarmEvent',{name:this.sensorName});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSonsorEvent(id).then(response => {
        this.form = response.data;
        if(this.form.threshold!=null && this.form.threshold.split(',').length > 1 && this.form.expression == 'BETWEEN') {
          this.thresholds.start = this.form.threshold.split(',')[0]
          this.thresholds.end = this.form.threshold.split(',')[1]
        }
        else if(this.form.threshold!=null){
          this.thresholds.start = this.form.threshold
        }
        this.open = true;
        this.title = this.$t('deviceData.editAlarmEvent',{name:this.sensorName});
      });
    },
    /** 提交按钮 */
    submitForm() {
      let thresholds = '';
      if(this.thresholds.start!=null) thresholds = this.thresholds.start;
      if(this.thresholds.end!=null && this.form.expression == 'BETWEEN') thresholds =  thresholds + ',' +this.thresholds.end;
      this.form.threshold = thresholds;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSonsorEvent(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.successful'));
              this.open = false;
              this.getList();
            });
          } else {
            addSonsorEvent(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.successful'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('common.deleteData',{name:row.name})).then(function() {
        return delSonsorEvent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.successful'));
      }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.line{
  text-align: center !important;
}
</style>